package com.daxue.configtest.utils;

import com.daxue.configtest.domian.RemoteConfig;
import com.daxue.configtest.domian.RemoteConfig.ConfigType;
import com.daxue.configtest.exception.impl.BadArgumentException;
import lombok.experimental.UtilityClass;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ByteArrayResource;
import org.yaml.snakeyaml.error.YAMLException;

import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;

/**
 * @author daxue0929
 * @date 2023/3/25
 */

@UtilityClass
public class RemoteConfigUtils {
    public static Properties convert(final RemoteConfig config) throws BadArgumentException {

        if (RemoteConfig.ConfigType.PROPERTIES.equals(config.getType())) {
            try {
                Properties properties = new Properties();
                properties.load(new StringReader(config.getValue()));
                return properties;
            } catch (IOException e) {
                throw new BadArgumentException(e);
            }
        } else if (ConfigType.YAML.equals(config.getType()) || ConfigType.YML.equals(config.getType())) {
            YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(new ByteArrayResource(config.getValue().getBytes()));
            try {
                return yamlFactory.getObject();
            } catch (YAMLException e) {
                throw new BadArgumentException(e);
            }
        }
        throw new BadArgumentException("Unsupported config format: " + config.getType());
    }
}
